package zvalidation

import (
	"context"

	"gitee.com/youkelike/zerror"
	userv1 "gitee.com/youkelike/zvalidation/example/api/proto/gen/user/v1"
)

// 每个模型都有一个这样的文件

func (v *Validator) ValidateUserRules() Rules {
	// 通用的密码校验函数
	validatePassword := func() ValidatorFunc {
		return func(value any) error {
			return isValidPassword(value.(string))
		}
	}

	// 定义各字段的校验逻辑，通过一个 map 实现模块化和简化
	return Rules{
		"Password":    validatePassword(),
		"OldPassword": validatePassword(),
		"NewPassword": validatePassword(),
		"UserID": func(value any) error {
			if value.(string) == "" {
				return zerror.ErrInvalidArgument.WithMessage("userID cannot be empty")
			}
			return nil
		},
		"Username": func(value any) error {
			if !isValidUsername(value.(string)) {
				return zerror.ErrInvalidArgument.WithMessage("Username must consist of letters, digits, and underscores only, and its length must be between 3 and 20 characters.")
			}
			return nil
		},
		"Nickname": func(value any) error {
			if len(value.(string)) >= 30 {
				return zerror.ErrInvalidArgument.WithMessage("nickname must be less than 30 characters")
			}
			return nil
		},
		"Email": func(value any) error {
			return isValidEmail(value.(string))
		},
		"Phone": func(value any) error {
			return isValidPhone(value.(string))
		},
		"Limit": func(value any) error {
			if value.(int64) <= 0 {
				return zerror.ErrInvalidArgument.WithMessage("limit must be greater than 0")
			}
			return nil
		},
		"Offset": func(value any) error {
			return nil
		},
	}
}

// ValidateCreateUserRequest 校验 CreateUserRequest 结构体的有效性.
func (v *Validator) ValidateCreateUserRequest(ctx context.Context, req *userv1.CreateUserRequest) error {
	return ValidateAllFields(req, v.ValidateUserRules())
}
